﻿using System;
using DBProvider.Providers;
using System.Web.UI.WebControls;

namespace HealthCommunity.Controls
{
	public partial class UCQuestionNewest : System.Web.UI.UserControl
	{
		private IQuestionProvider _QuestionProvider;

		protected void Page_Load(object sender, EventArgs e)
		{
			//if (!IsPostBack)
			{
				BindQuestion();
			}
		}

		protected void rptQuestion_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
		{
			if (e.Item.DataItem != null)
			{
				var dataItem = e.Item.DataItem as DBProvider.Question;
				var ltrUserName = e.Item.FindControl("ltrUserName") as Literal;
				var ltrAddTime = e.Item.FindControl("ltrAddTime") as Literal;
				var hlQuestionContent = e.Item.FindControl("hlQuestionContent") as HyperLink;

				ltrAddTime.Text = dataItem.QuestionAddTime.GetValueOrDefault().ToString();
				ltrUserName.Text = dataItem.User.UserCName;
				hlQuestionContent.Text = dataItem.QuestionContent;
				if (dataItem.QuestionContent.Length > 40)
				{
					hlQuestionContent.Text = dataItem.QuestionContent.Substring(0, 40) + "...";
				}
				hlQuestionContent.ToolTip = dataItem.QuestionContent;
				hlQuestionContent.NavigateUrl = "~/QuestionDetail.aspx?questionid=" + dataItem.QuestionID.ToString();
			}
		}

		private void BindQuestion()
		{
			if (_QuestionProvider == null)
			{
				_QuestionProvider = new QuestionProvider();
			}

			var user = SiteContext.Current.CurrentUser;

			if (user != null && user.Role != null && user.Role.RoleName.Equals("admin"))
			{
				var drugStore = SiteContext.Current.CurrentDrugStore;

				if (drugStore != null)
				{
					rptQuestion.DataSource = _QuestionProvider.GetNewQuestions(6, drugStore.DrugStoreID);
					rptQuestion.DataBind();
				}
			}
			else
			{
				if (user != null && user.DrugStoreID.GetValueOrDefault(0) > 0)
				{
					rptQuestion.DataSource = _QuestionProvider.GetNewQuestions(6, user.DrugStoreID.Value, user.UserID);
					rptQuestion.DataBind();
				}
			}
		}
	}
}
